package com.cty.controller;

import com.cty.pojo.Picture;
import com.cty.service.PictureService;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @Auther: com.cty
 * @Date: 2020/3/26 22:02
 * @Description:
 * @version: 1.0
 */
@Controller
public class PictureController {
    Logger log = Logger.getLogger(PictureController.class);

    @Resource
    private PictureService pictureServiceImpl;  // 按命名注入

    @RequestMapping("upload")
    public String upload(MultipartFile file, HttpServletRequest req) throws IOException {
        // 获取文件名后缀
        String fileName = file.getOriginalFilename();  // 获取文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));  // 获取文件名后缀
        log.debug("上传广告图："+fileName);

        // 将文件名存入数据库
        Picture picture = new Picture();
        picture.setPath(fileName);
        this.pictureServiceImpl.insPictureService(picture);
        log.info("广告图路径已上传到数据库");

        System.out.println(req.getServletContext().getRealPath("files").toString());

        // 判断上传数据类型并上传到指定路径
        if(suffix.equalsIgnoreCase(".png") || suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".jpeg")){
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(req.getServletContext().getRealPath("files"),fileName));
            log.debug("广告图已上传到指定目录");
            return "redirect:/index.jsp";
        }else {
            return "typeError";
        }
    }

    @RequestMapping("show")
    public String show(Model model){
        model.addAttribute("pictures", this.pictureServiceImpl.selAllService());
        log.debug("已从数据库查询所有广告图");
        return "page";
    }

    @RequestMapping("delete")
    public String delete(int id){
        this.pictureServiceImpl.delPictureService(id);
        log.debug("已删除id="+id+"的广告图");
        return "redirect:show";
    }
}
